<template>
	<view class="container">
		<!-- 搜索栏和筛选 -->
		<view style="padding: 20rpx 26rpx 0 26rpx;">
			<SearchBox v-model="searchValue" @search="search" @input="input" :autofocus="false" />
		</view>
		<!-- 分类 -->
		<WarehouseCategoryRow @open-selector="openSelector" />
		<!-- 已选标签 -->
		<view class="selected-tags" v-if="selectedTags.length">
			<view v-for="(tag, i) in selectedTags" :key="i" class="tag-item" style="display: flex; align-items: center; background-color: rgba(198, 40, 43, 0.1); border-radius: 30rpx; padding: 10rpx 20rpx; font-size: 20rpx; color: #C02C38; margin-right: 10rpx;">
				<text>{{ tag.label }}</text>
				<text 
					@click="removeFilter(tag.key)" 
					style="margin-left: 8rpx; font-size: 28rpx; color: #C02C38; cursor: pointer;"
				>
					×
				</text>
			</view>
		</view>

		<!-- 仓库列表 -->
			<view v-if="!loading && warehouseList.length" class="warehouse-list">
				<view v-for="(item, idx) in warehouseList" :key="item.id || idx" class="warehouse-card">
					<WarehourseItem :item="item" @reserve="goReserve(item)" @contact="goContact(item)" />
				</view>
				<view v-if="hasMore" class="load-more" @click="loadMore">
					<uni-load-more :status="loadMoreStatus" :content-text="loadMoreText"></uni-load-more>
			</view>
			</view>

			<view v-else-if="!loading && !warehouseList.length" class="empty-state">
				<text class="empty-text">暂无相关仓库信息</text>
			</view>
		<!-- 通用选择弹窗 -->
		<uni-popup ref="selectorPopup" type="bottom" background-color="#fff">
			<view class="selector-popup">
				<view class="selector-popup__header">
					<text class="selector-popup__title">{{ currentSelector.title }}</text>
					<text class="selector-popup__close" @tap="closeSelector">关闭</text>
		</view>
				<scroll-view scroll-y style="max-height: 60vh;">
					<view v-for="(opt, i) in currentSelector.options" :key="opt.value" class="selector-option" :class="{ 'selector-option--active': opt.value === currentSelector.selectedValue }" @tap="selectOption(opt)">
						<text class="selector-option__label">{{ opt.label }}</text>
						<text v-if="opt.value === currentSelector.selectedValue" class="selector-option__check">✓</text>
		</view>
				</scroll-view>
		</view>
		</uni-popup>
	</view>
</template>

<script>
import WarehourseItem from '@/components/warehourseItem.vue';
import SearchBox from '@/components/SearchBox.vue';
import WarehouseCategoryRow from '@/components/WarehouseCategoryRow.vue';
import { API } from '@/utils/api.js';
import { 
  getFullUrl, 
  processWarehouseUrls, 
  processNewsUrls 
} from '@/utils/url-helper.js';
	export default {
		components:{
			WarehourseItem,
			SearchBox,
			WarehouseCategoryRow
		},
		data() {
			return {
				searchValue: '',
				// 接口数据
				parkList: [],
				parkAreaList: [],
				warehouseTypes: [],
				warehouseTags: [],
				warehouseList: [],
				// 分页
				page: 1,
				size: 10,
				// 选择器 & 筛选
				filters: {
					parkId: null,
					areaId: null,
					typeId: null,
					tagId: null,
					parkLabel: '',
					areaLabel: '',
					typeLabel: '',
					tagLabel: ''
				},
				currentSelector: {
					key: '',
					title: '',
					options: [],
					selectedValue: null
				}
			}
		},
		computed: {
			selectedTags() {
				const tags = [];
				if (this.filters.areaId) tags.push({ key: 'area', label: `区域：${this.filters.areaLabel}` });
				if (this.filters.parkId) tags.push({ key: 'park', label: `园区：${this.filters.parkLabel}` });
				if (this.filters.tagId) tags.push({ key: 'tag', label: `行业：${this.filters.tagLabel}` });
				if (this.filters.typeId) tags.push({ key: 'type', label: `库形：${this.filters.typeLabel}` });
				return tags;
			}
		},
		async onLoad() {
			try {
				await Promise.allSettled([
					this.loadParkList(),
					this.loadParkAreaList(),
					this.loadWarehouseTypes(),
					this.loadWarehouseTags()
				]);
			} catch (e) {
				console.error('基础数据加载失败', e);
			} finally {
				await this.loadWarehouseList();
			}
		},
		// 添加分享功能
		onShareAppMessage() {
			let shareTitle = '优质仓库资源'
			if (this.searchValue) {
				shareTitle = `搜索"${this.searchValue}"的仓库资源`
			} else if (this.selectedTags.length > 0) {
				const tagNames = this.selectedTags.map(tag => tag.label.split('：')[1]).join('、')
				shareTitle = `${tagNames}相关仓库`
			}
			
			return {
				title: shareTitle,
				path: '/pages/warehouse/warehouse',
				imageUrl: '/static/assets/share/warehouse-share.png'
			}
		},
		// 分享到朋友圈
		onShareTimeline() {
			let shareTitle = '优质仓库资源'
			if (this.searchValue) {
				shareTitle = `搜索"${this.searchValue}"的仓库资源`
			} else if (this.selectedTags.length > 0) {
				const tagNames = this.selectedTags.map(tag => tag.label.split('：')[1]).join('、')
				shareTitle = `${tagNames}相关仓库`
			}
			
			return {
				title: shareTitle,
				imageUrl: '/static/assets/share/warehouse-share.png'
			}
		},
		methods: {
			async loadParkList() {
				try {
					const res = await API.park.getList({pageNumber: 1, pageSize: 1000});
					this.parkList = Array.isArray(res?.rows) ? res.rows : (Array.isArray(res) ? res : []);
				} catch (e) {
					console.error('获取园区列表失败', e);
				}
			},
			async loadParkAreaList() {
				try {
					const res = await API.park.getAreaList({pageNumber: 1, pageSize: 1000});
					this.parkAreaList = Array.isArray(res?.rows) ? res.rows : (Array.isArray(res) ? res : []);
				} catch (e) {
					console.error('获取园区区域列表失败', e);
				}
			},
			async loadWarehouseTypes() {
				try {
					const res = await API.warehouse.getWarehouseTypes({pageNumber: 1, pageSize: 1000});
					this.warehouseTypes = Array.isArray(res?.rows) ? res.rows : (Array.isArray(res) ? res : []);
				} catch (e) {
					console.error('获取仓库类型失败', e);
				}
			},
			async loadWarehouseTags() {
				try {
					const res = await API.warehouse.getWarehouseTags({pageNumber: 1, pageSize: 1000});
					this.warehouseTags = Array.isArray(res?.rows) ? res.rows : (Array.isArray(res) ? res : []);
				} catch (e) {
					console.error('获取仓库标签失败', e);
				}
			},
			normalizeOptions(list, labelKeys = [], valueKeys = []) {
				if (!Array.isArray(list)) return [];
				const pickFirst = (obj, keys, fallback) => {
					for (let i = 0; i < keys.length; i += 1) {
						const k = keys[i];
						if (obj && obj[k] !== undefined && obj[k] !== null && obj[k] !== '') return obj[k];
					}
					return fallback;
				};
				return list.map((it, idx) => ({
					label: pickFirst(it, labelKeys.concat(['label','name','title','parkName','areaName','typeName','tagName']), `选项${idx+1}`),
					value: pickFirst(it, valueKeys.concat(['id','value','code','key']), idx),
					raw: it
				}));
			},
			openSelector(key) {
				const config = {
					park: { title: '选择园区', list: this.parkList, labelKeys: ['parkName','name','label'], valueKeys: ['id','parkId','value'] },
					area: { title: '选择区域', list: this.parkAreaList, labelKeys: ['areaName','name','label'], valueKeys: ['id','areaId','value'] },
					type: { title: '选择库形', list: this.warehouseTypes, labelKeys: ['typeName','name','label'], valueKeys: ['id','typeId','value'] },
					tag: { title: '选择行业', list: this.warehouseTags, labelKeys: ['tagName','name','label'], valueKeys: ['id','tagId','value'] }
				};
				const c = config[key];
				if (!c) return;
				const options = this.normalizeOptions(c.list, c.labelKeys, c.valueKeys);
				const selectedValue = (
					key === 'park' ? this.filters.parkId :
					key === 'area' ? this.filters.areaId :
					key === 'type' ? this.filters.typeId :
					key === 'tag' ? this.filters.tagId : null
				);
				this.currentSelector = { key, title: c.title, options, selectedValue };
				this.$refs.selectorPopup && this.$refs.selectorPopup.open();
			},
			closeSelector() {
				this.$refs.selectorPopup && this.$refs.selectorPopup.close();
			},
			selectOption(opt) {
				if (!opt) return;
				console.log("opt", opt)
				if (this.currentSelector.key === 'park') {
					this.filters.parkId = opt.value;
					this.filters.parkLabel = opt.label;
				}
				if (this.currentSelector.key === 'area') {
					this.filters.areaId = opt.value;
					this.filters.areaLabel = opt.label;
				}
				if (this.currentSelector.key === 'type') {
					this.filters.typeId = opt.value;
					this.filters.typeLabel = opt.label;
				}
				if (this.currentSelector.key === 'tag') {
					this.filters.tagId = opt.value;
					this.filters.tagLabel = opt.label;
				}
				this.currentSelector.selectedValue = opt.value;
				this.closeSelector();
				this.page = 1;
				this.loadWarehouseList();
			},
			removeFilter(key) {
				if (key === 'park') { this.filters.parkId = null; this.filters.parkLabel = ''; }
				if (key === 'area') { this.filters.areaId = null; this.filters.areaLabel = ''; }
				if (key === 'type') { this.filters.typeId = null; this.filters.typeLabel = ''; }
				if (key === 'tag') { this.filters.tagId = null; this.filters.tagLabel = ''; }
				this.page = 1;
				this.loadWarehouseList();
			},
			async loadWarehouseList() {
				try {
					const params = {
						page: this.page,
						size: this.size
					};
					// 搜索关键字
					if (this.searchValue && this.searchValue.trim()) {
						params.keyword = this.searchValue.trim();
					}
					// 园区ID
					if (this.filters.parkId) {
						params.parkId = this.filters.parkId;
					}
					// 仓库类型
					if (this.filters.typeId) {
						params.warehouseType = this.filters.typeId;
					}
					// 区域ID
					if (this.filters.areaId) {
						params.parkAreaId = this.filters.areaId;
					}
					// 仓库标签（行业ID）
					if (this.filters.tagId) {
						params.industryDataId = this.filters.tagId;
					}
					const res = await API.warehouse.getList(params);
					if (Array.isArray(res?.rows)) {
						this.warehouseList = res.rows;
					} else if (Array.isArray(res)) {
						this.warehouseList = res;
					} else {
						this.warehouseList = [];
					}
					 if (res.code === 200 ) {
					console.log(res.rows);
					const warehouseData = res;
					if (warehouseData.rows) {
						this.warehouseList = processWarehouseUrls(warehouseData.rows);
						this.warehouseList.forEach(item => {
							if(item.vrLink && item.vrLink.length > 0){
								item.warehouseTags = [{
									tagName: 'VR看仓',
									tagImage: '/static/assets/home/home-icon-vr.png',
									tagId: -2
								},...item.warehouseTags];
							}
							if(item.isRecommend){
								item.warehouseTags = [{
									tagName: '推荐',
									tagImage: '/static/assets/home/home-isRecommend.png',
									tagId: -1
								},...item.warehouseTags];
							}
						});
						this.hasMore = warehouseData.rows.length >= this.pageSize;
					} else {
						this.warehouseList = [];
						this.hasMore = false;
					}
				}
				} catch (e) {
					console.error('获取仓库列表失败', e);
					this.warehouseList = [];
				}
			},
			search() {
				this.page = 1
				this.loadWarehouseList()
			},
			input(value) {
				this.searchValue = value
			}
		}
	}
</script>

<style lang="less" scoped>
	.container {
		background: #ffffff;
		min-height: 100vh;
		padding-bottom: 120rpx;
	}

	.search-bar {
		display: flex;
		align-items: center;
		margin: 20rpx 16rpx 0 16rpx;
	}

	.search-input {
		flex: 1;
		background: #ffffff;
		border-radius: 30rpx;
		padding: 16rpx;
		font-size: 28rpx;
		border: 1rpx solid #e8e8e8;
	}

	.filter-btn {
		margin-left: 12rpx;
		background: #ffffff;
		border: 1rpx solid var(--primary-color);
		border-radius: 30rpx;
		color: var(--primary-color);
		display: flex;
		align-items: center;
		padding: 0 18rpx;
	}

	.category-row {
		display: flex;
		justify-content: space-around;
		margin: 16rpx 0 8rpx 0;
		
	}

	.category-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		font-size: 26rpx;
		padding: 10rpx 30rpx;
	}

	.category-row-bg {
		width: 110rpx;
		height: 110rpx;
		border-radius: 16rpx;
		background-image: url('/static/assets/source/category-row-bg.png');
		background-size: 100% 100%;
		background-position: center;
		display: flex;
		align-items: center;
		justify-content: center;
		position: relative;
		overflow: hidden;
	}

	.load-more {
	padding: 20rpx 0;
	text-align: center;
}

.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 80rpx 40rpx;
	min-height: 500rpx;
	
	.empty-text {
		color: #999;
		font-size: 28rpx;
		margin-bottom: 30rpx;
	}
}

	.category-row-bg__img {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		z-index: 0;
		pointer-events: none;
	}

	.category-row-icon {
		width: 40rpx;
		height: 40rpx;
		object-fit: contain;
		position: relative;
		z-index: 1;
	}

	.selected-tags {
		display: flex;
		flex-wrap: wrap;
		gap: 10rpx;
		color: #C6282B;
		padding: 0 26rpx;
	}

	.warehouse-list {
	.warehouse-card {
		margin-bottom: 20rpx;
	}
	}

	.warehouse-info {
		margin-bottom: 12rpx;
	}

	.desc {
		color: #888;
		font-size: 24rpx;
		margin-bottom: 4rpx;
	}

	.address,
	.area {
		display: flex;
		align-items: center;
		color: #888;
		font-size: 24rpx;
		margin-bottom: 4rpx;
	}

	.tags {
		margin: 8rpx 0;
		display: flex;
		flex-wrap: wrap;
	}

	.card-btns {
		display: flex;
		justify-content: space-between;
		margin-top: 12rpx;
	}

	.btn {
		width: 45%;
	}

	/* 选择弹窗样式 */
	.selector-popup {
		padding: 24rpx 24rpx 12rpx 24rpx;
	}
	.selector-popup__header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding-bottom: 12rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}
	.selector-popup__title {
		font-size: 30rpx;
		font-weight: 600;
	}
	.selector-popup__close {
		font-size: 26rpx;
		color: #888;
	}
	.selector-option {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 24rpx 8rpx;
		border-bottom: 1rpx solid #f7f7f7;
	}
	.selector-option--active .selector-option__label {
		color: var(--primary-color);
		font-weight: 600;
	}
	.selector-option__label {
		font-size: 28rpx;
	}
	.selector-option__check {
		color: var(--primary-color);
		font-size: 28rpx;
	}
</style>